package com.zx.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.zx.entity.User;
import com.zx.service.UserService;
import com.zx.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZX
 * @date 2021/4/14
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController
{

    @Resource
    private UserService userService;

    @PostMapping(value = "/login")
    public Map<String, Object> login(User user)
    {

        log.info("用户名：{}", user.getName());
        log.info("password: {}", user.getPassword());

        Map<String, Object> map = new HashMap<>();
        try
        {
            User userDB = userService.login(user);
            Map<String, String> payload = new HashMap<>();
            payload.put("id", userDB.getId());
            payload.put("name", userDB.getName());
            String token = JwtUtils.getToken(payload);
            map.put("state", true);
            map.put("msg", "登录成功");
            map.put("token", token);
            return map;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", e.getMessage());
            map.put("token", "");
        }
        return map;
    }

    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        DecodedJWT verify = JwtUtils.verify(token);
        String id = verify.getClaim("id").asString();
        String name = verify.getClaim("name").asString();
        log.info("用户id：{}", id);
        log.info("用户名: {}", name);

        //TODO 业务逻辑
        Map<String, Object> map = new HashMap<>();
        map.put("state", true);
        map.put("msg", "请求成功");
        return map;
    }
}
